package com.ljx.NoteBody.controller;

import com.ljx.NoteBody.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
public class FileController {

    @Value("${Image.Path}")
    String ImagePath;

    @Value("${Image.URL}")
    String URL;

    @Transactional
    @PostMapping
    public R<String> upload(@RequestParam("file") MultipartFile file){
        // 获取原文件名的后缀
        String s = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));

        // 使用UUID重新生成文件名，防止文件名重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + s;

        try {
            // 若文件目录不存在就创建一个
            File nFile = new File(ImagePath);
            if(!nFile.exists()){
                nFile.mkdirs();
            }
            // 转存文件
            file.transferTo(new File(ImagePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
//            throw new MyException("图片存放错误");
        }

        return R.success(URL + "api/upload/" + fileName);
    }

    @GetMapping("/{name}")
    public void download(@PathVariable("name") String name,
                         HttpServletResponse httpServletResponse) throws Exception{

        // 输入流
        FileInputStream fileInputStream = new FileInputStream(new File(ImagePath + name));

        // 输出流，将文件写回浏览器
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();

        httpServletResponse.setContentType("image/jpeg");

        int len = 0;
        byte[] bytes = new byte[1024];
        // 读取文件，数据存入bytes数组中
        while((len = fileInputStream.read(bytes)) != -1){
            // 从bytes中写出文件到输出流中
            servletOutputStream.write(bytes, 0, len);
            // 刷新
            servletOutputStream.flush();
        }

        // 关闭资源
        servletOutputStream.close();
        fileInputStream.close();

    }
}
